import type { VercelRequest, VercelResponse } from "@vercel/node";

export default async function handler(req: VercelRequest, res: VercelResponse) {
  const { lng, lat } = req.query;
  const AMAP_KEY = process.env.AMAP_KEY || "";

  if (!lng || !lat) {
    return res.status(400).json({ error: "缺少 lng 或 lat 参数" });
  }

  try {
    // 获取城市编码
    const geoRes = await fetch(
      `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${AMAP_KEY}`
    );
    const geoData = await geoRes.json();
    const cityCode = geoData?.regeocode?.addressComponent?.adcode ?? "110101";

    // 获取天气信息
    const weatherRes = await fetch(
      `https://restapi.amap.com/v3/weather/weatherInfo?city=${cityCode}&key=${AMAP_KEY}`
    );
    const weatherData = await weatherRes.json();

    res.status(200).json(weatherData);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "服务器错误" });
  }
}

